package com.lear.rrbus.view;

import java.util.Calendar;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.lear.rrbus.R;
import com.lear.rrbus.data.BusAddress;
import com.lear.rrbus.utils.Utils;

public class MainView extends Activity implements OnClickListener {

	private ImageButton btnSearchLine;
	private ImageButton btnSearchStation;
	private Button btnSearchBus;
	private Button btnSearchWeb;
	private EditText lineInput;
	private EditText stationInput;
	private RadioGroup radioAlarm;
	private CheckBox checkDir;

	private int storedAlarm;
	private String storedLine;
	private String storedStation;
	private Intent busIntent;
	private SharedPreferences settings;
	private Boolean isAutoSearch;

	private void init() {
		settings = getSharedPreferences(Utils.APPNAME, MODE_WORLD_WRITEABLE);

		checkDir = (CheckBox) findViewById(R.id.check_dir);
		radioAlarm = (RadioGroup) findViewById(R.id.radio_alarm);

		btnSearchLine = (ImageButton) findViewById(R.id.btn_search_line);
		btnSearchStation = (ImageButton) findViewById(R.id.btn_search_station);
		btnSearchBus = (Button) findViewById(R.id.btn_bus_search);
		btnSearchWeb = (Button) findViewById(R.id.btn_myweb);

		btnSearchLine.setOnClickListener(this);
		btnSearchStation.setOnClickListener(this);
		btnSearchBus.setOnClickListener(this);
		btnSearchWeb.setOnClickListener(this);

		lineInput = (EditText) findViewById(R.id.ed_input_line);
		stationInput = (EditText) findViewById(R.id.ed_input_station);

		loadInfo();

		lineInput.setFilters(Utils.autoUpCase);

		lineInput.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
				readInfo();
				String newText = s.toString();
				if (TextUtils.isEmpty(storedLine)) {
					settings.edit().putBoolean(Utils.NEEDLOADLINE, true)
							.commit();
				} else if (!storedLine.equals(newText)) {
					settings.edit().putBoolean(Utils.NEEDLOADLINE, true)
							.commit();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		OnKeyListener keyEnter = new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					// Shut down soft keyboard
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
					search(2);
					return true;
				}
				return false;
			}
		};

		lineInput.setOnKeyListener(keyEnter);
		stationInput.setOnKeyListener(keyEnter);

		// Setting auto input station when change the swithcer
		checkDir.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (Utils.ISLEAR) {
					int timeHour = Calendar.getInstance().get(
							Calendar.HOUR_OF_DAY);
					int timeMin = Calendar.getInstance().get(Calendar.MINUTE);
					if (isChecked) {
						if (timeHour > 21 && timeMin > 20 && timeHour < 22) {
							stationInput.setText(getResources().getString(
									R.string.my_station_dn));
						} else if (timeHour > 18 && timeHour < 20) {
							stationInput.setText(getResources().getString(
									R.string.my_station_dn));
						} else {
							stationInput.setText(getResources().getString(
									R.string.my_station_dn2));
						}
					} else {
						stationInput.setText(getResources().getString(
								R.string.my_station_up));
					}
				}
			}
		});

		// Initial the direction
		int timeHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
		int timeMin = Calendar.getInstance().get(Calendar.MINUTE);
		if (Utils.ISLEAR) {
			if (timeHour > 21 && timeMin > 20 && timeHour < 22) {
				checkDir.setChecked(true);
				stationInput.setText(getResources().getString(
						R.string.my_station_dn));
			} else if (timeHour > 20) {
				checkDir.setChecked(true);
				stationInput.setText(getResources().getString(
						R.string.my_station_dn2));
			} else if (timeHour > 18) {
				checkDir.setChecked(true);
				stationInput.setText(getResources().getString(
						R.string.my_station_dn));
			} else if (timeHour < 9) {
				checkDir.setChecked(false);
				stationInput.setText(getResources().getString(
						R.string.my_station_up));
			} else {
				checkDir.setChecked(timeHour < 12 ? false : true);
			}
		} else {
			checkDir.setChecked(timeHour < 12 ? false : true);
		}
	}

	private void autoSearch() {
		if (isAutoSearch) {
			search(2);
		}
	}

	private void loadInfo() {

		if (storedLine != null) {
			lineInput.setText(storedLine);
		}
		if (storedStation != null) {
			stationInput.setText(storedStation);
		}

		switch (storedAlarm) {
		case -1:
			radioAlarm.check(R.id.radiooff);
			break;
		case 1:
			radioAlarm.check(R.id.radio0);
			break;
		case 2:
			radioAlarm.check(R.id.radio1);
			break;
		case 3:
			radioAlarm.check(R.id.radio2);
			break;
		}
	}

	public void onClick(View v) {
		if (v == btnSearchBus) {
			search(Utils.SEARCH_BUS);
		} else if (v == btnSearchLine) {
			search(Utils.SEARCH_LINE);
		} else if (v == btnSearchStation) {
			search(Utils.SEARCH_STATION);
		}

		else if (v == btnSearchWeb) {
			busIntent = new Intent(this, LearWebView.class);
			busIntent.putExtra(Utils.BROWSE,
					getResources().getString(R.string.text_defaultpage));
			busIntent.putExtra(Utils.BROWSER, true);
			startActivityForResult(busIntent, 1);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// full screen
		// int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
		// this.getWindow().setFlags(flag, flag);
		// getActionBar().setBackgroundDrawable(
		// getResources().getDrawable(R.color.actionbar));
		setContentView(R.layout.main_view);
		setActionBar();
		readInfo();
		init();
		autoSearch();
	}

	private void setActionBar() {
		ActionBar mActionBar = getActionBar();
		// mActionBar.setBackgroundDrawable(getResources().getDrawable(
		// R.color.actionbar));
		mActionBar.setDisplayShowHomeEnabled(false);
		// mActionBar.setDisplayHomeAsUpEnabled(true);
		// mActionBar.setDisplayShowCustomEnabled(true);
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getMenuInflater().inflate(R.menu.activity_main_view, menu);
	// return true;
	// }

	// @Override
	// public boolean onPrepareOptionsMenu(Menu menu) {
	// SharedPreferences prefs = getSharedPreferences(Utils.APPNAME,
	// MODE_WORLD_READABLE);
	// isAutoSearch = prefs.getBoolean("AUTO_SEARCH", false);
	// if (isAutoSearch) {
	// ((MenuItem) menu.findItem(R.id.menu_autosearch)).setVisible(false);
	// ((MenuItem) menu.findItem(R.id.menu_unautosearch)).setVisible(true);
	// } else {
	// ((MenuItem) menu.findItem(R.id.menu_autosearch)).setVisible(true);
	// ((MenuItem) menu.findItem(R.id.menu_unautosearch))
	// .setVisible(false);
	// }
	//
	// return super.onPrepareOptionsMenu(menu);
	// }

	// @Override
	// public boolean onOptionsItemSelected(MenuItem item) {
	// switch (item.getItemId()) {
	// case R.id.menu_autosearch:
	// isAutoSearch = true;
	// break;
	// case R.id.menu_unautosearch:
	// isAutoSearch = false;
	// default:
	// break;
	// }
	// SharedPreferences prefs = getSharedPreferences(Utils.APPNAME,
	// MODE_WORLD_READABLE);
	// prefs.edit().putBoolean("AUTO_SEARCH", isAutoSearch).commit();
	// return super.onOptionsItemSelected(item);
	// }

	@Override
	public void onPause() {
		super.onPause();
		saveInfo();
	}

	@Override
	public void onRestart() {
		super.onRestart();
		readInfo();
		loadInfo();
	}

	private void readInfo() {
		SharedPreferences pref = getSharedPreferences(Utils.APPNAME,
				MODE_WORLD_READABLE);
		int tempAlarm = pref.getInt(Utils.STOREDALAEM, -1);
		String tempLine = pref.getString(Utils.STOREDLINE, null);
		String tempStation = pref.getString(Utils.STOREDSTATION, null);

		storedAlarm = tempAlarm;
		storedLine = tempLine == null ? null : tempLine;
		storedStation = tempStation == null ? null : tempStation;
		isAutoSearch = pref.getBoolean("AUTO_SEARCH", false);
	}

	private void saveInfo() {
		int checkedId = radioAlarm.getCheckedRadioButtonId();
		switch (checkedId) {
		case R.id.radiooff:
			storedAlarm = -1;
			break;
		case R.id.radio0:
			storedAlarm = 1;
			break;
		case R.id.radio1:
			storedAlarm = 2;
			break;
		case R.id.radio2:
			storedAlarm = 3;
			break;
		}
		// Auto add "Station"
		String tempStation = stationInput.getText().toString();
		if (!TextUtils.isEmpty(tempStation)) {
			tempStation = tempStation.contains(Utils.STATIONTAG) ? tempStation
					: tempStation + Utils.STATIONTAG;
		}

		Editor editor = getSharedPreferences(Utils.APPNAME, MODE_WORLD_READABLE)
				.edit();
		editor.putString(Utils.STOREDLINE, lineInput.getText().toString());
		editor.putString(Utils.STOREDSTATION, tempStation);
		editor.putInt(Utils.STOREDALAEM, storedAlarm);
		editor.commit();
	}

	private void search(int index) {

		storedLine = lineInput.getText().toString();
		storedStation = stationInput.getText().toString();
		busIntent = new Intent(this, LearWebView.class);

		saveInfo();

		switch (index) {
		case Utils.SEARCH_LINE:
			if (!storedLine.isEmpty()) {
				busIntent.putExtra(Utils.BROWSE, (new BusAddress(storedLine,
						checkDir.isChecked()).toString()));
				startActivityForResult(busIntent, 1);
			} else {
				Toast.makeText(this,
						getResources().getString(R.string.input_warn),
						Toast.LENGTH_SHORT).show();
			}
			break;
		case Utils.SEARCH_STATION:
			if (!storedStation.isEmpty()) {
				busIntent.putExtra(Utils.BROWSE,
						(new BusAddress(storedStation).toString()));
				startActivityForResult(busIntent, 1);
			} else {
				Toast.makeText(this,
						getResources().getString(R.string.input_warn),
						Toast.LENGTH_SHORT).show();
			}
			break;
		case Utils.SEARCH_BUS:
			if (!storedLine.isEmpty()) {
				busIntent = new Intent(this, BusResultView.class);
				String searchKey = new BusAddress(storedLine,
						checkDir.isChecked()).toString();
				settings.edit().putString(Utils.SEARCHKEY, searchKey).commit();
				busIntent.putExtra(Utils.BROWSE, searchKey);
				startActivityForResult(busIntent, 1);
			} else {
				Toast.makeText(this,
						getResources().getString(R.string.input_warn),
						Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}

}
